<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>03.列表过滤</title>
  </head>
  <style>
    ul {
      list-style-type: disc;
    }
  </style>

  <body>
    <div id="app">
      <ul>
        <h1>信息展示</h1>
        <input type="text" placeholder="请输入姓名" v-model="value">
        <h2>{{value}}</h2>
        <li v-for="(item,index) in newArr" :key="index">{{item}}</li>
      </ul>
    </div>
  </body>
  <script src="../js/vue.js"></script>
  <script type="text/javascript">
    new Vue({
      el: "#app",
      data: {
        message: "对象列表展示",
        value: '',
        arr: [{
            name: '马冬梅',
            age: 19,
            gender: 'female'
          },
          {
            name: '周冬雨',
            age: 25,
            gender: 'female'
          },
          {
            name: '周杰伦',
            age: 36,
            gender: 'male'
          },
          {
            name: '桂伦镁',
            age: 39,
            gender: 'female'
          },
        ],
      },
      methods: {
        //直接操作了原数据，会引起原数据的丢失
        /* searchName: function (value) {
          // console.log(this.value);
          for (let i = 0; i < this.arr.length; i++) {
            let str = this.arr[i].name;
            console.log(str, typeof (str));
            if (str.indexOf(this.value) == -1) {
              this.arr.splice(i, 1)
            }
          }
        } */
      },
      watch: {
        /* 
        如果使用监视，直接操作data里的面的数组会对原数据造成破坏
        */
        /*  value: function (newValue, oldValue) {
           const arr = this.arr.filter((item, index) => {
             // console.log(item, index);
             return item.name.indexOf(newValue) !== -1
           })
           this.arr = arr
         } */
      },
      computed: {
        /* 
        使用计算属性创建你一个新的数组和原来的数组独立存在，互相不影响
        */
        newArr: function () {
          const {
            value,
            arr
          } = this;
          return arr.filter((item, index) => {
            return item.name.indexOf(value) !== -1
          })
        }
      }
    })
  </script>

</html>